const { PrismaClient } = require("@prisma/client");
const bcrypt = require("bcrypt");

const prisma = new PrismaClient();

async function checkAndCreateAdmin() {
  try {
    console.log("检查管理员账号...");

    // 检查是否存在管理员账号
    const admin = await prisma.adminUser.findFirst({
      where: { username: "admin" },
    });

    if (admin) {
      console.log("✅ 管理员账号已存在:");
      console.log(`   ID: ${admin.id}`);
      console.log(`   用户名: ${admin.username}`);
      console.log(`   邮箱: ${admin.email}`);
      console.log(`   状态: ${admin.isActive ? "启用" : "禁用"}`);
      console.log(`   创建时间: ${admin.createdAt}`);
    } else {
      console.log("❌ 管理员账号不存在，正在创建...");

      // 创建管理员账号
      const hashedPassword = await bcrypt.hash("123456", 10);
      const newAdmin = await prisma.adminUser.create({
        data: {
          username: "admin",
          email: "admin@aiproducthome.com",
          password: hashedPassword,
          isActive: true,
        },
      });

      console.log("✅ 管理员账号创建成功:");
      console.log(`   ID: ${newAdmin.id}`);
      console.log(`   用户名: ${newAdmin.username}`);
      console.log(`   邮箱: ${newAdmin.email}`);
      console.log(`   密码: 123456`);
    }

    // 测试登录
    console.log("\n测试登录...");
    const testAdmin = await prisma.adminUser.findFirst({
      where: { username: "admin" },
    });

    if (testAdmin) {
      const isValid = await bcrypt.compare("123456", testAdmin.password);
      if (isValid) {
        console.log("✅ 密码验证成功");
      } else {
        console.log("❌ 密码验证失败");
      }
    }
  } catch (error) {
    console.error("❌ 错误:", error);
  } finally {
    await prisma.$disconnect();
  }
}

checkAndCreateAdmin();
